<template>
  <div>
    <el-dialog width="40%" :title="id == null ? '销售员添加' : '销售员编辑'" :visible.sync="visible" :loading="true" :close-on-click-modal="false">

      <el-form ref="main-form" status-icon :model="mainQuery" :rules="rules" label-width="130px" label-position="left" :inline="false" style="width: 450px;">
        <el-form-item label="用户名" size="mini" prop="username">
          <el-input placeholder="" v-model="mainQuery.username" @keyup.enter.native="submit" :readonly="!!id" :disabled="loading" clearable></el-input>
        </el-form-item>


        <template v-if="resetPassword || id == null">
          <el-form-item label="密码" size="mini" prop="password">
            <el-input placeholder="" type="password" v-model="mainQuery.password" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
          <el-form-item label="确认密码" size="mini" prop="passwordConfirm">
            <el-input placeholder="" type="password" v-model="mainQuery.passwordConfirm" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
        </template>

        <el-form-item size="mini" v-if="id != null">
          <el-button v-if="!resetPassword" @click="handleResetPassword" type="warning" :disabled="loading">重置密码</el-button>
          <el-button v-else @click="handleResetPassword" :disabled="loading">取消</el-button>
        </el-form-item> 

        <el-form-item size="mini" v-if="id != null" label="Google验证码密钥">
          <el-button @click="handleResetGoogleAuthSecret" type="primary" :disabled="loading">重置</el-button>
          <el-button @click="handleViewGoogleAuthSecret" v-if="!isViewingGoogleAuthSecret">查看</el-button>
          <el-input style="width: 180px; margin: 0 10px;" ref="googleAuthSecret" v-model="mainQuery.googleAuthSecret" readonly v-if="isViewingGoogleAuthSecret"></el-input>
          <el-link type="primary" @click="copyData('googleAuthSecret', mainQuery.googleAuthSecret)" v-if="isViewingGoogleAuthSecret">复制</el-link>
        </el-form-item> 

        <el-form-item label="昵称" size="mini" prop="nick">
          <el-input placeholder="" v-model="mainQuery.nick" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" size="mini" prop="realName">
          <el-input placeholder="" v-model="mainQuery.realName" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" size="mini" prop="mobile">
          <el-input placeholder="" v-model="mainQuery.mobile" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="Email" size="mini" prop="email">
          <el-input placeholder="" v-model="mainQuery.email" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>

        <el-form-item label="关联商户" size="mini" prop="mchIdList">
          <el-select
            v-model="mainQuery.mchIdList"
            filterable
            remote
            reserve-keyword
            multiple
            placeholder="请输入关键词搜索"
            :remote-method="fetchMchOptions"
            :loading="mchLoading">
            <el-option
              v-for="item in mchOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户状态" size="mini" prop="status">
          <el-select v-model="mainQuery.status" placeholder="未选择" :disabled="loading">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close" size="mini">取 消</el-button>
        <el-button @click="submit" size="mini" type="primary" :loading="loading">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import ApiMain from '@/api/system.member';
import RoleApiMain from '@/api/system.role';
import ApiMch from '@/api/mch.info';
import { mapState, mapActions } from 'vuex'

export default {
  mixins: [
  ],
  props: [
    'statusOptions',
  ],
  data () {
    return {

      visible         : false,
      popDeleteVisible: false,
      loading         : false,
      mchLoading: false,

      mchOptions: [],

      mainQueryRaw: null,
      mainQuery   : {
        username       : '',
        password       : '',
        passwordConfirm: '',
        nick           : '',
        realName       : '',
        email          : '',
        mobile         : '',
        roleId         : '',
        mchIdList      : [],
        status         : 1 ,
      },

      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 99, message: '长度在 4 到 99 个字符', trigger: 'blur' }
        ],
        nick: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        ],
        roleId: [
          { required: true, message: '请选择用户角色', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
        ],

        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],

        passwordConfirm: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value !== this.mainQuery.password) {
                callback(new Error('两次输入密码不一致'));
              }
              else {
                callback();
              }
            }, 
            trigger: 'blur' 
          },
        ],
      },

      id  : null,
      data: null,
      resetPassword: false,
      isViewingGoogleAuthSecret: false
    }
  },
  mounted () {
    this.mainQueryRaw = Object.copy(this.mainQuery);
  },

  methods: {

    ...mapActions('d2admin/account', [
      'logout'
    ]),

    show (id = null) {

      this.reset();

      if (id) {
        this.id = id;
        this.fetchData();
      } else {
        this.fetchMchOptions();
      }

      this.fetchSalesRoleOptions()

      this.visible = true;
    },

    close () {
      this.visible = false;
      this.$emit('dialog-close');
    },

    reset () {

      this.mainQuery = Object.copy(this.mainQueryRaw);
      this.$refs['main-form'] && this.$refs['main-form'].resetFields();

      this.id   = null;
      this.data = null;
      this.resetPassword = false;
      this.isViewingGoogleAuthSecret = false;
    },

    handleResetPassword () {
      this.resetPassword = ! this.resetPassword;
    },

    // 重置GoogleAuthSecret
    handleResetGoogleAuthSecret () {
      this.$confirm('确定要重置Google验证码密钥吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ApiMain.resetGoogleAuthSecret({id: this.id}).then((data) => {
          console.log(data)
          this.$message({message: '操作成功', type: 'success'});
          this.fetchData();
        });
      });
    },

    // 查看GoogleAuthSecret
    handleViewGoogleAuthSecret () {
      this.isViewingGoogleAuthSecret = true
    },

    async fetchData () {

      this.loading = true;

      try {
        var re = await ApiMain.info({id: this.id});
        this.data = re;
      } catch (err) {
        this.data = null;
      }

      this.renderData();

      this.loading = false;
    },

    fetchMchOptions (search, id) {
      this.mchLoading = true;
      ApiMch.option({ search: search, id: id ? id : '' }).then(re => {
        this.mchOptions = re
        this.mchLoading = false
      })
    },

    async fetchSalesRoleOptions () {
      var re = await RoleApiMain.getOptions({ extraType: 1 });
      if (re.length < 1) {
        this.visible = false
        this.$message.error('请先设置销售角色')
      }
      this.mainQuery.roleId = re[0].value
    },

    renderData () {

      this.mainQuery.username = this.data.username;
      this.mainQuery.realName = this.data.realName;
      this.mainQuery.nick     = this.data.nick;
      this.mainQuery.email    = this.data.email;
      this.mainQuery.mobile   = this.data.mobile;
      this.mainQuery.roleId   = this.data.roleId;
      this.mainQuery.googleAuthSecret = this.data.googleAuthSecret;
      this.mainQuery.mchIdList= this.data.mchIdList;
      this.mainQuery.status   = this.data.status;

      this.fetchMchOptions('', this.data.mchIdList);

    },

    verifyForm () {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit () {

      if (! this.verifyForm()) return false;

      this.loading = true;

      try {
        this.id ? await this.submitSet() : await this.submitAdd();
      } catch (err) {}

      this.loading = false;
    },

    async submitAdd () {
      await ApiMain.add(this.mainQuery);
      this.$message({message: '添加成功', type: 'success'});
      this.close();
    },

    async submitSet () {

      var req = Object.copy(this.mainQuery);

      req.id = this.id;

      if (! this.resetPassword) {
        delete req.password;
        delete req.passwordConfirm;
      }

      let resp = await ApiMain.set(req);
      if (resp.isMe) {
        this.$message({message: '修改成功，将重新登录', type: 'success'});
        this.logout();
      } else {
        this.$message({message: '修改成功', type: 'success'});
        this.close();
      }
    },

    copyData (ref, val) {
      this.$refs[ref].select()
      document.execCommand('copy');
      this.$message({message: '已复制', type: 'success'});
    },

  }
}
</script>

<style>

</style>
